﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;

namespace BlogTruyen
{
    public partial class Genre : PhoneApplicationPage
    {
        ViewModels.Genre Data;
        private string catId;

        public Genre()
        {
            InitializeComponent();

            Data = new ViewModels.Genre();
            DataContext = Data;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            topbar.Title = NavigationContext.QueryString["title"];
            if (!Data.isLoaded)
            {
                var webClient = API.GetWebClient();
                webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
                webClient.DownloadStringAsync(new Uri(String.Format("http://blogtruyen.com{0}",NavigationContext.QueryString["url"]), UriKind.Absolute));
                busyIndicator.IsRunning = true;
            }
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (API.CheckWebClient(e))
            {
                var regex = new Regex(@"CategoryID = (?<id>\d+);");
                Match match = regex.Match(e.Result);
                catId = match.Groups["id"].ToString();
                ExecuteSearch();
            }
        }

        private void ExecuteSearch()
        {
            if (Data.nextPage == null) return;
            var webClient = API.GetWebClient();
            webClient.DownloadStringCompleted += search_DownloadStringCompleted;
            webClient.DownloadStringAsync(new Uri(String.Format("http://blogtruyen.com/ListStory/GetCategory?CategoryID={1}&OrderBy=1&PageIndex={0}", Data.nextPage,catId), UriKind.Absolute));
        }

        private void search_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (API.CheckWebClient(e))
            {
                Data.LoadHtml(e.Result);
            }
            busyIndicator.IsRunning = false;
        }

        private void topbar_ExecuteSearch(object sender, EventArgs e)
        {
            if (topbar.SearchQuery.Length == 0) return;
            NavigationService.Navigate(new Uri(String.Format("/Search.xaml?keyword={0}", HttpUtility.UrlEncode(topbar.SearchQuery)), UriKind.Relative));
            topbar.SearchQuery = "";
        }

        private void llsStories_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            var itemSource = llsStories.ItemsSource;
            if (itemSource[itemSource.Count - 1] == e.Container.Content)
            {
                ExecuteSearch();
            }
        }

        private void Story_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var story = ((FrameworkElement)sender).DataContext as Models.Story;
            NavigationService.Navigate(new Uri(string.Format("/StoryDetails.xaml?url={0}&title={1}", story.url, HttpUtility.UrlEncode(story.title)), UriKind.Relative));
        }
    }
}